import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import { getToken } from '@/utils/auth'
import Layout from '@/layout'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 配置NProgress
NProgress.configure({ showSpinner: false })

Vue.use(Router)

// 路由白名单
const whiteList = ['/login']

export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true,
    meta: { title: '登录' }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index'),
        meta: { title: '仪表板', icon: 'el-icon-video-camera-solid' }
      }
    ]
  },
  {
    path: '/orders',
    component: Layout,
    name: 'Orders',
    meta: { title: '订单管理', icon: 'el-icon-s-order' },
    children: [
      {
        path: 'list',
        name: 'OrderList',
        component: () => import('@/views/orders/list'),
        meta: { title: '订单列表' },
        hidden: true

      },
      {
        path: 'delivery',
        name: 'Delivery',
        component: () => import('@/views/orders/delivery/index'),
        meta: { title: '配送管理' },
        hidden: true
      },
      {
        path: 'delivery/track/:orderNo',
        name: 'DeliveryTrack',
        component: () => import('@/views/orders/delivery/track'),
        meta: { title: '配送跟踪', activeMenu: '/orders/delivery' },
        hidden: true
      },
      {
        path: 'push',
        name: 'OrderPush',
        component: () => import('@/views/order/push.vue'),
        meta: { title: '订单推送', icon: 'el-icon-s-promotion' }
      }
    ]
  },
  // {
  //   path: '/goods',
  //   component: Layout,
  //   redirect: '/goods/list',
  //   name: 'Goods',
  //   meta: { title: '商品管理', icon: 'el-icon-goods' },
  //   children: [
  //     {
  //       path: 'list',
  //       name: 'GoodsList',
  //       component: () => import('@/views/goods/list'),
  //       meta: { title: '商品列表' }
  //     }
  //   ]
  // },
  {
    path: '/products',
    component: Layout,
    name: 'Products',
    meta: { title: '商品管理', icon: 'el-icon-goods' },
    children: [
      {
        path: 'list',
        name: 'ProductList',
        component: () => import('@/views/goods/list'),
        meta: { title: '商品列表' }
      },
      {
        path: 'category',
        name: 'ProductCategory',
        component: () => import('@/views/goods/category'),
        meta: { title: '商品分类' }
      },
      {
        path: 'price',
        name: 'GoodsPrice',
        component: () => import('@/views/goods/price'),
        meta: { title: '价格管理' },
        hidden:true
      },
      {
        path: 'edit/:id?',
        name: 'GoodsEdit',
        component: () => import('@/views/goods/edit'),
        meta: { title: '商品编辑' },
        hidden: true
      }
    ]
  },
 
  {
    path: '/customers',
    component: Layout,
    name: 'Customers',
    meta: { title: '客户管理', icon: 'el-icon-user' },
    children: [
      {
        path: 'list',
        name: 'CustomerList',
        component: () => import('@/views/customers/list'),
        meta: { title: '客户列表' }
      },
      {
        path: 'level',
        name: 'MemberLevel',
        component: () => import('@/views/customers/level'),
        meta: { title: '会员等级' }
      }
    ]
  },
  {
    path: '/salespeople',
    component: Layout,
    name: 'Salespeople',
    meta: { title: '销售员管理', icon: 'el-icon-s-custom' },
    children: [
      {
        path: 'list',
        name: 'SalespeopleList',
        component: () => import('@/views/salespeople/list'),
        meta: { title: '销售员列表' }
      },
      {
        path: 'stats',
        name: 'SalespeopleStats',
        component: () => import('@/views/salespeople/stats'),
        meta: { title: '业绩统计' }
      }
    ]
  },

  {
    path: '/monitor',
    component: Layout,
    children: [
      {
        path: 'dashboard',
        name: 'MonitorDashboard',
        component: () => import('@/views/monitor/Dashboard'),
        meta: { title: '监控仪表板', icon: 'el-icon-data-line' }
      }
    ]
  },
  {
    path: '*',
    redirect: '/404',
    hidden: true
  }
]

const createRouter = () => new Router({
  mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})

const router = createRouter()

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 开启进度条
  NProgress.start()

  // 获取token
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // 已登录且要跳转的页面是登录页
      next({ path: '/' })
      NProgress.done()
    } else {
      // 判断当前用户是否已拉取完user_info信息
      const hasRoles = store.getters['auth/roles'] && store.getters['auth/roles'].length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          // 获取用户信息
          await store.dispatch('auth/getInfo')
          next()
        } catch (error) {
          // 获取用户信息失败，清除token并跳转登录页
          await store.dispatch('auth/resetToken')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      // 其他没有访问权限的页面将被重定向到登录页面
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // 结束进度条
  NProgress.done()
})

export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher
}

export default router 